using System;
using System.Collections.Generic;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace MapControl.Misc
{
    public class RenderInBox
    {
        Rectangle box;
        Font font;
        string text;
        StringFormat format;

        public RenderInBox(Rectangle box, Graphics graphics, string text, string fontFamily, int startFontSize)
        {
            this.box = box;
            this.text = text;

            bool fits = false;
            int size = startFontSize;
            do
            {
                if (font != null)
                    font.Dispose();

                font = new Font(fontFamily, size, FontStyle.Regular, GraphicsUnit.Pixel);

                SizeF stringSize = graphics.MeasureString(text, font, box.Width, format);

                fits = (stringSize.Height < box.Height);
                size -= 2;
            } while (!fits);

            graphics.Dispose();

            format = new StringFormat();
            format.Alignment = StringAlignment.Center;
            format.LineAlignment = StringAlignment.Center;
        }

        public void Render(Graphics graphics, Brush brush)
        {
            graphics.DrawString(text, font, brush, box, format);
        }
    }
}
